export default class WaterEffect {
    constructor(containerId) {
      this.container = document.getElementById(containerId);
      this.canvas = document.createElement('canvas');
      this.ctx = this.canvas.getContext('2d');
      this.container.appendChild(this.canvas);
      this.waveHeight = [8, 8, 12];
      this.waveLength = 0.01;
      this.waveSpeed = [0.02, 0.03, 0.05];
      this.offsets = [0, 0, 0];
      this.animationFrameId = null;
      this.waveBaseHeight = 100;

      this.resizeCanvas();
      window.addEventListener('resize', () => this.resizeCanvas());
      this.draw();
    }

    resizeCanvas() {
      this.canvas.width = this.container.clientWidth;
      this.canvas.height = this.container.clientHeight;
    }

    draw() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      let gradient = this.ctx.createLinearGradient(0, this.canvas.height / 2, 0, this.canvas.height);
      gradient.addColorStop(0, `rgba(105, 163, 184, 1)`);
      gradient.addColorStop(1, `rgba(160, 204, 220, 1)`);

      this.ctx.fillStyle = gradient;
      // this.ctx.fillStyle = 'rgba(248, 249, 251, 1)'; // 背景颜色
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

      for (let i = 0; i < this.waveHeight.length; i++) {
        this.ctx.beginPath();
        for (let x = 0; x < this.canvas.width; x++) {
          let y = (this.canvas.height / 100 * this.waveBaseHeight + (i == 2 ? -20 : 0)) + Math.sin((x * this.waveLength) + this.offsets[i]) * this.waveHeight[i];
          this.ctx.lineTo(x, y);
        }
        this.ctx.lineTo(this.canvas.width, this.canvas.height);
        this.ctx.lineTo(0, this.canvas.height);
        this.ctx.closePath();

        let gradient = this.ctx.createLinearGradient(0, this.canvas.height / 2, 0, this.canvas.height);
        gradient.addColorStop(0, `rgba(115, 233, 245, 0.2)`);
        gradient.addColorStop(1, `rgba(248, 249, 251, 0.2)`);
        // gradient.addColorStop(0, `rgba(115, 233, 245, 0.7)`);
        // gradient.addColorStop(1, `rgba(248, 249, 251, 0.5)`);

        this.ctx.fillStyle = gradient;
        this.ctx.fill();

        // 更新偏移量
        this.offsets[i] += this.waveSpeed[i];
      }
      this.offsets[0] += this.waveSpeed[0] * 0.5;
      this.offsets[1] += this.waveSpeed[1] * 0.5;

      this.animationFrameId = requestAnimationFrame(() => this.draw());
    }

    destroy() {
      cancelAnimationFrame(this.animationFrameId);
      this.container.removeChild(this.canvas);
    }

    updateWaveBaseHeight(countdownTime, totalTime) {
        this.waveBaseHeight = countdownTime / totalTime * 100;
    }
  }